package com.serena.da.rest.services.deploy;

import com.serena.da.rest.common.GlobalContext;
import com.serena.da.rest.common.Utils;
import com.serena.da.rest.http_helpers.Response;

import java.io.File;
import java.util.HashMap;

/**
 * Global Environment Service
 *
 * @author Spitkovskyi Igor
 */
public class GlobalEnvironmentService extends SraDeployService {
    private static GlobalEnvironmentService globalEnvService;

    private GlobalEnvironmentService() throws Exception {
        super();
    }

    public static GlobalEnvironmentService getInstance() throws Exception {
        if (globalEnvService == null) {
            globalEnvService = new GlobalEnvironmentService();
        }
        return globalEnvService;
    }

    private String getRestUrlGlobalEnv() {
        String METHOD_GLOBAL_ENV = "globalEnvironment";
        return getRestUrl(METHOD_GLOBAL_ENV);
    }

    /**
     * Create global environment
     */
    public Response createGlobalEnvironment(String envName, String envDescription) throws Exception {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("envName", envName);
        hashMap.put("envDescription", envDescription);

        String jsonString = Utils.replaceJsonTemplateKeys("CreateGlobalEnvironment.js", hashMap);

        return executeRequest(getRestUrlGlobalEnv(), Method.PUT, jsonString, GlobalContext.GLOBAL_ENV_PREFIX);
    }

    /**
     * import global environment from json template
     */
    public Response importEnvironment(String envName, String envDescription) throws Exception {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("envName", envName);
        hashMap.put("envDescription", envDescription);

        String jsonString = Utils.replaceJsonTemplateKeys("CreateGlobalEnvironment.js", hashMap);

        String url = getRestUrlGlobalEnv() + "/import";
        return executeRequest(url, Method.POST, jsonString.getBytes());
    }

    // this is just an example of how to import file, created by Igor
    public Response importEnvironmentFromFile(String fileName) throws Exception {
        String templateFilesLocation = "/json_templates/";
        File sourceJson = getJsonFile(templateFilesLocation + fileName);
        return executeRequest(getRestUrlGlobalEnv() + "/import", Method.POST, sourceJson);
    }
}

